use crate::core::CTX;
use crate::domain::dto::module_dto::{ModuleCreateRequest, ModulePageRequest, ModulePageResponse, ModuleUpdateRequest};
use crate::domain::dto::{PageRes};
use crate::domain::entity::module_entity::ModuleEntity;
use crate::mapper::{module_mapper};
use crate::utils;

/// module_pages 模型分页查询
pub async fn module_pages(param: ModulePageRequest) -> rbatis::Result<PageRes<ModulePageResponse>> {
    let (num,size) = utils::tool::page_tools(param.page.clone().unwrap(), param.limit.clone().unwrap());
    let list = module_mapper::select_module_page(&mut CTX.db.clone(), num, size, param.name.clone(), param.biz_id.clone()).await?;
    let total = module_mapper::select_module_count(&mut CTX.db.clone(), param.name.clone(), param.biz_id.clone()).await?;
    Ok(PageRes {
        page: param.page.clone().unwrap(),
        limit: param.limit.clone().unwrap(),
        total,
        row: list,
    })
}

/// module_create 模型创建
pub async fn module_create(param: ModuleCreateRequest) -> rbatis::Result<bool> {
    let exist = module_mapper::exit_same_name(&mut CTX.db.clone(), param.name.as_str(), None).await?;
    if exist {
        return Err(rbatis::Error::from("存在相同的名称"))
    }
    let data: ModuleEntity = param.into();
    let result = ModuleEntity::insert(&mut CTX.db.clone(), &data).await?;
    Ok(result.rows_affected == 1)
}

/// module_update 模型更新
pub async fn module_update(param: ModuleUpdateRequest) -> rbatis::Result<bool> {
    let exist = module_mapper::exit_same_name(&mut CTX.db.clone(), param.name.as_str(), Some(param.id.clone())).await?;
    if exist {
        return Err(rbatis::Error::from("存在相同的名称"))
    }
    let mut data = module_mapper::select_one_by_id(&mut CTX.db.clone(), param.id.clone()).await?;
    data.biz_id = param.biz_id;
    data.module_name = param.name;
    data.module_about = param.about;
    let result = ModuleEntity::update_by_column(&mut CTX.db.clone(), &data, "id").await?;
    Ok(result.rows_affected == 1)
}